package com.example.forum.controller;

import com.example.forum.annotation.LoginRequired;
import com.example.forum.domain.Flag;
import com.example.forum.domain.LoginTicket;
import com.example.forum.domain.User;
import com.example.forum.service.UserService;
import com.example.forum.utils.ActiveStatus;
import com.example.forum.utils.HostHolder;
import com.example.forum.utils.SimpleUtils;
import com.example.forum.utils.Timeout;
import com.sun.mail.imap.protocol.MODSEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

@Controller
public class UserController implements ActiveStatus,Timeout {
    @Autowired
    private UserService userService;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private Flag flag;
    @Autowired
    private HostHolder hostHolder;
    @Value("${forum.path.domain}")
    private String domain;
    @Value("${forum.path.uploadpath}")
    private String uploadPath;

    @RequestMapping("/active")
    @ResponseBody
    public String active(String activeCode,int id){
        int status = userService.active(activeCode, id);
        if(status==ACTIVE_FAIL){
            return "激活失败,激活码错误，回到<a href='http://localhost:9999/index'>首页</a>";
        }
        if(status==ACTIVE_SUCCESS){
            return "恭喜您，牛客网账号激活成功，快去<a href='http://localhost:9999/login'>登录</a>吧！";
        }
        return "该账号已经激活，无需重复激活！回到<a href='http://localhost:9999/index'>首页</a>";
    }

    @RequestMapping("/register")
    public String register(){
        return "site/register";
    }

    @RequestMapping(value = "/register.do",method = RequestMethod.POST)
    public String registerDo(User user, Model model){
        Map<String, String> map = userService.registerUser(user);
        if(map==null || map.isEmpty()){  //注册成功
            model.addAttribute("seconds",5);
            model.addAttribute("result","注册成功，我们已经向您的邮箱中发送了一封激活邮件，请尽快激活！");
            return "site/operate-result";
        }
        //注册失败
        Set<String> keys = map.keySet();
        for(String key:keys){
            model.addAttribute(key,map.get(key));
        }
        return "site/register";
    }

    @RequestMapping("/login")
    public String login(){
        return "site/login";
    }

    @RequestMapping("/login.do")
    public String loginDo(String username, String password, boolean rememberme,String checkCode,
                          Model model, HttpSession session, HttpServletResponse response){
        String sysCheckCode = (String) session.getAttribute("checkCode");
        if(!sysCheckCode.equalsIgnoreCase(checkCode)){
            model.addAttribute("checkCodeError","验证码错误");
            return "site/login";
        }
        int timeoutSeconds=rememberme?REMEMBERME_TIMEOUT:DEFAULT_TIMEOUT;
        Map<String, Object> map = userService.login(username, password,timeoutSeconds);
        if(map.containsKey("ticket")){
            //登录成功,将ticket保存到cookie中发送给客户端
            Cookie cookie=new Cookie("ticket",((LoginTicket)map.get("ticket")).getTicket());
            cookie.setPath(contextPath);
            cookie.setMaxAge(timeoutSeconds);
            response.addCookie(cookie);
            flag.setFlag(true);
            return "redirect:/index";
        }
        //登录失败后将错误信息返回给登录页面
        Set<String> keys = map.keySet();
        for(String key:keys){
            model.addAttribute(key,map.get(key));
        }
        return "site/login";
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        //将登录状态值为false
        flag.setFlag(false);
        return "site/login";
    }

    //账号设置
    @LoginRequired
    @RequestMapping("/setting")
    public String setting(){
        return "site/setting";
    }

    //上传头像
    @LoginRequired
    @RequestMapping("/upHeadImage")
    public String upHeadImage(MultipartFile headImage,Model model){
        //上传文件为空
        if(headImage==null || headImage.isEmpty()){
            model.addAttribute("fileUploadError","文件不能为空");
            return "site/setting";
        }
        String originalFilename = headImage.getOriginalFilename();
        String[] splits = originalFilename.split("[.]");
        if(!splits[1].equalsIgnoreCase("jpg") && !splits[1].equalsIgnoreCase("png") && !splits[1].equalsIgnoreCase("jpeg")){
            model.addAttribute("fileUploadError","文件格式不正确");
            return "site/setting";
        }
        //将文件名加上时间戳
        originalFilename = splits[0]+System.currentTimeMillis()+"."+splits[1];
        try {
            //保存文件
            String headerUrl=uploadPath+"/"+originalFilename;
            headImage.transferTo(new File(headerUrl));
            //更改用户给头像信息
            User user = hostHolder.getUser();
            //设置用户头像url(web访问的路径)
            String webHeadUrl = domain+contextPath+"headImage/"+originalFilename;
            userService.upHeadImage(webHeadUrl,user.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/index";
    }

    //加载头像
    @RequestMapping("/headImage/{fileName}")
    public void  headImage(HttpServletResponse response,@PathVariable("fileName") String fileName){
        //得到文件名后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        response.setContentType("image/"+suffix);
        FileInputStream fis=null;
        try {
            ServletOutputStream os = response.getOutputStream();
            //读取用户头像
            fis=new FileInputStream(uploadPath+"/"+fileName);
            byte[] buffer=new byte[1024];
            int b=0;
            while ((b=fis.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //修改密码
    @LoginRequired
    @RequestMapping("/updatePassword")
    public String updatePassword(String oldPassword,String newPassword,String confirmPassword,Model model){
        Map<String, String> map = userService.updatePassword(oldPassword, newPassword, confirmPassword);
        if(map.isEmpty()){  //修改密码成功
            return "redirect:/index";
        }
        //修改密码失败
        Set<String> keys = map.keySet();
        for(String key:keys){
            model.addAttribute(key,map.get(key));
        }
        return "site/setting";
    }
}
